﻿using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace VisionCloud.Domain.Filters
{
    /// <summary>
    /// 显示枚举的Description
    /// </summary>
    public class EnumSchemaFilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            if (!context.Type.IsEnum) return;

            StringBuilder sb = new StringBuilder();
            Enum.GetNames(context.Type).ToList().ForEach(name =>
            {
                Enum e = (Enum)Enum.Parse(context.Type, name);
                var desc = GetDescription(context.Type, e);
                string data;
                if (string.IsNullOrEmpty(desc))
                    data = $"{Convert.ToInt32(e)} = {name}；";
                else
                    data = $"{desc}：{Convert.ToInt32(e)} = {name}；";

                sb.AppendLine(data);
            });

            schema.Description = sb.ToString();
            schema.Type = context.Type.Name;
            schema.Format = context.Type.Name;
        }

        /// <summary>
        /// 获取属性的DescriptionAttribute内容
        /// </summary>
        /// <param name="t"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private static string GetDescription(Type t, object value)
        {
            foreach (MemberInfo mInfo in t.GetMembers())
            {
                if (mInfo.Name == t.GetEnumName(value))
                {
                    foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo))
                    {
                        if (attr.GetType() == typeof(DescriptionAttribute))
                        {
                            return (attr as DescriptionAttribute).Description;
                        }
                    }
                }
            }

            return string.Empty;
        }
    }
}
